import sys
import os
from sqlalchemy.orm import Session

# 添加项目根目录到Python路径
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

# 导入数据库和模型
from database import SessionLocal, engine, Base
from models import DictType, DictItem
import logging

# 配置日志
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

# 默认数据字典配置
default_dicts = [
    {
        "name": "用户状态",
        "code": "user_status",
        "description": "用户账号状态",
        "items": [
            {"label": "启用", "value": "1", "sort_order": 1},
            {"label": "禁用", "value": "0", "sort_order": 2}
        ]
    },
    {
        "name": "无人机状态",
        "code": "drone_status",
        "description": "无人机运行状态",
        "items": [
            {"label": "正常", "value": "normal", "sort_order": 1},
            {"label": "维护中", "value": "maintenance", "sort_order": 2},
            {"label": "故障", "value": "fault", "sort_order": 3},
            {"label": "停用", "value": "disabled", "sort_order": 4}
        ]
    },
    {
        "name": "航线类型",
        "code": "route_type",
        "description": "飞行航线类型",
        "items": [
            {"label": "巡检", "value": "inspection", "sort_order": 1},
            {"label": "测绘", "value": "survey", "sort_order": 2},
            {"label": "监控", "value": "monitoring", "sort_order": 3},
            {"label": "运输", "value": "transport", "sort_order": 4}
        ]
    },
    {
        "name": "性别",
        "code": "gender",
        "description": "性别选项",
        "items": [
            {"label": "男", "value": "male", "sort_order": 1},
            {"label": "女", "value": "female", "sort_order": 2},
            {"label": "保密", "value": "secret", "sort_order": 3}
        ]
    }
]

def init_dicts(db: Session):
    """初始化数据字典"""
    logger.info("开始初始化数据字典...")
    
    # 遍历默认数据字典配置
    for dict_config in default_dicts:
        # 查找或创建字典类型
        dict_type = db.query(DictType).filter(
            DictType.code == dict_config["code"]
        ).first()
        
        if not dict_type:
            # 创建新的字典类型
            dict_type = DictType(
                name=dict_config["name"],
                code=dict_config["code"],
                description=dict_config["description"],
                is_active=True,
                sort_order=1
            )
            db.add(dict_type)
            db.commit()
            db.refresh(dict_type)
            logger.info(f"创建字典类型: {dict_config['name']}({dict_config['code']})")
        else:
            # 更新现有字典类型的信息
            dict_type.name = dict_config["name"]
            dict_type.description = dict_config["description"]
            dict_type.is_active = True
            db.commit()
            logger.info(f"更新字典类型: {dict_config['name']}({dict_config['code']})")
        
        # 处理字典项
        for item_config in dict_config["items"]:
            # 查找或创建字典项
            dict_item = db.query(DictItem).filter(
                DictItem.dict_type_id == dict_type.id,
                DictItem.value == item_config["value"]
            ).first()
            
            if not dict_item:
                # 创建新的字典项
                dict_item = DictItem(
                    dict_type_id=dict_type.id,
                    label=item_config["label"],
                    value=item_config["value"],
                    is_active=True,
                    sort_order=item_config["sort_order"]
                )
                db.add(dict_item)
                logger.info(f"  - 创建字典项: {item_config['label']}({item_config['value']})")
            else:
                # 更新现有字典项的信息
                dict_item.label = item_config["label"]
                dict_item.is_active = True
                dict_item.sort_order = item_config["sort_order"]
                logger.info(f"  - 更新字典项: {item_config['label']}({item_config['value']})")
    
    # 提交所有更改
    db.commit()
    logger.info("数据字典初始化完成")

def main():
    """主函数"""
    # 创建数据库会话
    db = SessionLocal()
    try:
        # 确保数据库表已创建
        Base.metadata.create_all(bind=engine)
        logger.info("数据库表检查完成")
        
        # 初始化数据字典
        init_dicts(db)
        
    except Exception as e:
        logger.error(f"初始化数据字典失败: {str(e)}")
        db.rollback()
        raise
    finally:
        db.close()

if __name__ == "__main__":
    main()